<script setup lang="ts">
import type { OssFile } from '#/api/system/oss/model';

import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';

import { useAccess } from '@vben/access';
import { VbenIcon } from '@vben/icons';

import { CopyOutlined } from '@ant-design/icons-vue';
import { useClipboard } from '@vueuse/core';
import {
  Button,
  Descriptions,
  DescriptionsItem,
  message,
  Tooltip,
} from 'ant-design-vue';
import { isFunction, isString } from 'lodash-es';

import { ossInfo } from '#/api/system/oss';
import { renderDict } from '#/utils/render';

const props = withDefaults(defineProps<Props>(), {
  columns: () => [],
  details: () => undefined,
  column: 1,
  labelWidth: 120,
  showExtraInfo: true,
});

const { hasAccessByCodes, hasAccessByRoles } = useAccess();

const isSuperAdmin = computed(() => hasAccessByRoles(['superadmin']));

interface Props {
  columns?: DetailsModalSchema[];
  column?: number; // 几列布局
  details?: any;
  labelWidth?: number | string;
  showExtraInfo?: boolean; // 是否显示额外字段，如ID、创建人和时间等
}

watch(
  () => props.details,
  async (details) => {
    console.log('详情组件watch：', details);
    if (details) {
      info.value = details;
      const ossColumns = props.columns.filter((item) => item.oss);
      if (ossColumns.length > 0) {
        for (const ossColumn of ossColumns) {
          const fieldName = ossColumn.fieldName;
          if (details?.[fieldName]) {
            const ossList: OssFile[] = await ossInfo([details[fieldName]]);
            if (ossList && ossList.length > 0) {
              info.value[`${fieldName}Data`] = ossList[0];
            }
          }
        }
      }
    }
  },
);

const info = ref<any>();
const basicColumns = ref([
  { label: '最后更新时间', fieldName: 'updateTime' },
  { label: '最后更新人', fieldName: 'updateByName' },
  { label: '创建时间', fieldName: 'createTime' },
  { label: '创建人', fieldName: 'createByName' },
]);
const descriptionsItemList = computed(() => {
  let columns: DetailsModalSchema[] = [...props.columns];

  if (props.showExtraInfo) {
    columns = [...props.columns, ...basicColumns.value];
  }

  if (isSuperAdmin.value && props.showExtraInfo) {
    columns.unshift({
      label: 'ID编号',
      fieldName: 'id',
      copy: true,
    });
  }

  return columns;
});

const { copy } = useClipboard({ legacy: true });

async function handleCopy(schema: any) {
  await (isFunction(schema.copy)
    ? copy(schema.copy(info.value))
    : copy(info.value[schema.fieldName]));
  message.success('复制成功');
}

const router = useRouter();

function handleViewLink(schema: any) {
  if (isFunction(schema.url)) {
    const routerUrl = schema.url(info.value);
    router.push(routerUrl);
  } else if (isString(schema.url)) {
    window.open(schema.url);
  } else {
    window.open(info.value[schema.fieldName]);
  }
}

// // 预览文件
// function handlePreviewFile(ossId: number | string) {
//
// }

onMounted(() => {
  // console.log('详情组件onMounted', props.details);
  if (props.details) {
    info.value = props.details;
  }
});
</script>

<template>
  <Descriptions
    v-if="info"
    size="small"
    :column="column"
    bordered
    :colon="true"
  >
    <template #extra>
      <slot name="extra"></slot>
    </template>
    <template v-for="(schema, index) in descriptionsItemList" :key="index">
      <DescriptionsItem
        v-if="!schema.dependencies || schema.dependencies?.if?.(info)"
        :label="schema.label"
        :span="schema.span || 1"
        :label-style="{ width: `${labelWidth}px` }"
      >
        <component
          v-if="schema.dictEnum"
          :is="
            renderDict(
              info[schema.fieldName],
              schema.dictEnum,
              !!schema.dictEnumFormatNumber,
            )
          "
        />
        <slot
          v-else-if="schema.custom"
          :name="schema.fieldName"
          :info="info"
        ></slot>
        <div v-else class="flex flex-wrap items-center">
          <template v-if="!schema.slots">
            <div v-if="schema.oss">
              <Button
                type="link"
                target="_blank"
                :title="`上传时间:${info[`${schema.fieldName}Data`]?.createTime}`"
                :href="info[`${schema.fieldName}Data`]?.url"
                class="flex items-center pl-0"
              >
                <template #icon>
                  <VbenIcon icon="mdi:file-eye-outline" />
                </template>
                {{ info[`${schema.fieldName}Data`]?.originalName }}
              </Button>
            </div>
            <div
              v-else-if="
                schema.url &&
                (!schema.accessCode || hasAccessByCodes([schema.accessCode]))
              "
            >
              <Button
                v-if="info[schema.fieldName]"
                type="link"
                class="flex items-center px-0"
                @click="handleViewLink(schema)"
              >
                <template #icon>
                  <VbenIcon icon="mynaui:link-solid" />
                </template>
                {{ info[schema.fieldName] }}
              </Button>
            </div>
            <span
              v-else
              :class="
                schema.textWrap
                  ? 'whitespace-pre-wrap break-words leading-relaxed'
                  : ''
              "
            >
              {{ info[schema.fieldName] }}
            </span>
          </template>
          <component
            v-if="schema.slots?.default"
            :is="schema.slots.default(info)"
          />
          <span
            v-if="
              (schema.copy === true || isFunction(schema.copy)) && !schema.oss
            "
          >
            <Tooltip :title="`复制${schema.label}`">
              <CopyOutlined
                v-if="info[schema.fieldName]"
                class="ml-[5px] cursor-pointer"
                @click="handleCopy(schema)"
              />
            </Tooltip>
          </span>
        </div>
        <slot :name="`${schema.fieldName}Extra`"></slot>
      </DescriptionsItem>
    </template>
  </Descriptions>
</template>
